/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Acceso.java
 *
 * Created on 22/12/2011, 10:56:44 PM
 */

package sst.Vistas;
import com.mysql.jdbc.Connection;

import de.javasoft.plaf.synthetica.SyntheticaBlueIceLookAndFeel;

import java.awt.event.KeyEvent;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import sst.Modelo.ConexionDB;


/**
 *
 * @author alberto
 */
public class Acceso extends javax.swing.JFrame {
    //ConexionDB db;
    Connection con;

    /** Creates new form Acceso */
    public Acceso() {
        //botonIngresar.addKeyListener(new PresionarTecla());
        try {
            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException ex) {
                JOptionPane.showMessageDialog(null, "Problemas con el driver de conexion", "Falla en driver ", JOptionPane.ERROR_MESSAGE);
                System.exit(0);
            }
            String URL = "jdbc:mysql://localhost/sst";
            try {
                con = (Connection) DriverManager.getConnection(URL,"root","alberto.1990");
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(null, "Problema con parametros de conexion, Verifique.", "Falla en conexion", JOptionPane.ERROR_MESSAGE);
                System.exit(0);
            }
            initComponents();
            //centrar ventana
            setLocationRelativeTo(null);


            java.sql.Statement consultaUsuarios = con.createStatement();
            java.sql.ResultSet res = consultaUsuarios.executeQuery("SELECT usuario FROM user");
            while (res.next()) {
                listaUsuarios.addItem(res.getString("usuario"));

            }

          con.setAutoCommit(true);
          con.close();
          con=null;
        } catch (SQLException ex) {
            Logger.getLogger(Acceso.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        listaUsuarios = new javax.swing.JComboBox();
        textPass = new javax.swing.JPasswordField();
        botonIngresar = new javax.swing.JButton();
        botonCancelar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Acceso");
        setAlwaysOnTop(true);
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });

        botonIngresar.setText("Ingresar");
        botonIngresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonIngresarActionPerformed(evt);
            }
        });

        botonCancelar.setText("Cancelar");
        botonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonCancelarActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("DejaVu Sans", 3, 13));
        jLabel1.setText("Usuario:");

        jLabel3.setFont(new java.awt.Font("DejaVu Sans", 1, 14));
        jLabel3.setText("Ingrese Datos Solicitados");

        jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sst/imagenes/password.png"))); // NOI18N

        jLabel2.setFont(new java.awt.Font("DejaVu Sans", 3, 13));
        jLabel2.setText("Contraseña:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel3))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(37, 37, 37)
                        .addComponent(botonIngresar, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(botonCancelar, javax.swing.GroupLayout.DEFAULT_SIZE, 139, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(listaUsuarios, 0, 185, Short.MAX_VALUE)
                            .addComponent(textPass, javax.swing.GroupLayout.DEFAULT_SIZE, 185, Short.MAX_VALUE))))
                .addGap(33, 33, 33)
                .addComponent(jLabel4)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel3)
                        .addGap(33, 33, 33)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(listaUsuarios, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(textPass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(botonCancelar)
                            .addComponent(botonIngresar)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(28, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void botonIngresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonIngresarActionPerformed
        try {
            ConexionDB conexion = new ConexionDB();
            String textoUsuario = listaUsuarios.getSelectedItem().toString();
            String textoContrasena = this.textPass.getText();
            textoContrasena = md5(textoContrasena);
            //System.out.print(textoContrasena);
            //System.out.print(textoContrasena + textoUsuario);
            boolean esValido = false;
            esValido = conexion.validarUsuario(textoUsuario, textoContrasena);
            if(esValido==true){

                //ingresar codigo para usuario valid
             //instancia de menuPrincipal
                Principal principal = new Principal();
                this.dispose(); //dispose eliminamos por completo la referencia de memoria
                principal.setVisible(true); //mostramos el frame 
           
            }else{
                System.out.print("NO");
            //agregar mensaje de error
            }
        conexion.cerrarConexion();
        } catch (SQLException ex) {
            Logger.getLogger(Acceso.class.getName()).log(Level.SEVERE, null, ex);
        }





    }//GEN-LAST:event_botonIngresarActionPerformed

    public static String md5(String input){
        String res = "";
        try {
            MessageDigest algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(input.getBytes());
            byte[] md5 = algorithm.digest();
            String tmp = "";
            for (int i = 0; i < md5.length; i++) {
                tmp = (Integer.toHexString(0xFF & md5[i]));
                if (tmp.length() == 1) {
                    res += "0" + tmp;
                } else {
                    res += tmp;
                }
            }
        } catch (NoSuchAlgorithmException ex) {}
        return res;
    }


    private void botonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonCancelarActionPerformed
        System.exit(0);
    }//GEN-LAST:event_botonCancelarActionPerformed

    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
       KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0,false);

    }//GEN-LAST:event_formKeyPressed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
         /*try
    {
      UIManager.setLookAndFeel(new SyntheticaBlueIceLookAndFeel());
        String key = "C1410294-61B64AAC-4B7D3039-834A82A1-37E5D695";
        String[] license = {"Licensee=AppWork UG" ,
        "LicenseRegistrationNumber=289416475",
        "Product=Synthetica",
        "LicenseType=Small Business License",
        "ExpireDate=--.--.----" ,
        "MaxVersion=2.999.999" };
        UIManager.put("Synthetica.license.info", license);
        UIManager.put("Synthetica.license.key", key);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }*/
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Acceso().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonCancelar;
    private javax.swing.JButton botonIngresar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    public javax.swing.JComboBox listaUsuarios;
    private javax.swing.JPasswordField textPass;
    // End of variables declaration//GEN-END:variables

}
